// 前端性能优化和样式治理系统
class FrontendOptimizer {
    constructor() {
        this.performanceMetrics = {
            pageLoadTimes: [],
            apiResponseTimes: [],
            memoryUsage: [],
            interactionDelays: []
        };
        
        this.styleRegistry = new Map();
        this.init();
    }

    init() {
        this.setupPerformanceMonitoring();
        this.setupStyleOptimization();
        this.setupErrorTracking();
        this.setupLazyLoading();
    }

    // 性能监控
    setupPerformanceMonitoring() {
        // 页面加载时间监控
        window.addEventListener('load', () => {
            const loadTime = performance.timing.loadEventEnd - performance.timing.navigationStart;
            this.recordMetric('pageLoadTimes', loadTime);
            
            if (loadTime > 3000) {
                console.warn(`页面加载时间过长: ${loadTime}ms`);
            }
        });

        // API响应时间监控
        this.monitorAPIRequests();
        
        // 内存使用监控
        this.monitorMemoryUsage();
        
        // 用户交互延迟监控
        this.monitorInteractionDelays();
    }

    // API请求监控
    monitorAPIRequests() {
        const originalFetch = window.fetch;
        
        window.fetch = async (...args) => {
            const startTime = Date.now();
            
            try {
                const response = await originalFetch(...args);
                const responseTime = Date.now() - startTime;
                
                this.recordMetric('apiResponseTimes', responseTime);
                
                if (responseTime > 5000) {
                    console.warn(`API响应时间过长: ${responseTime}ms`, args[0]);
                }
                
                return response;
            } catch (error) {
                const responseTime = Date.now() - startTime;
                this.recordMetric('apiResponseTimes', responseTime);
                throw error;
            }
        };
    }

    // 内存使用监控
    monitorMemoryUsage() {
        if (performance.memory) {
            setInterval(() => {
                const memory = performance.memory;
                this.recordMetric('memoryUsage', memory.usedJSHeapSize);
                
                if (memory.usedJSHeapSize > memory.jsHeapSizeLimit * 0.8) {
                    console.warn('内存使用接近限制，建议优化');
                }
            }, 30000);
        }
    }

    // 交互延迟监控
    monitorInteractionDelays() {
        let lastInteractionTime = Date.now();
        
        ['click', 'keydown', 'mousemove', 'scroll'].forEach(eventType => {
            document.addEventListener(eventType, () => {
                const delay = Date.now() - lastInteractionTime;
                if (delay > 100) { // 只记录超过100ms的延迟
                    this.recordMetric('interactionDelays', delay);
                }
                lastInteractionTime = Date.now();
            }, { passive: true });
        });
    }

    // 记录指标
    recordMetric(metricName, value) {
        this.performanceMetrics[metricName].push({
            value,
            timestamp: Date.now()
        });
        
        // 保持最近1000个记录
        if (this.performanceMetrics[metricName].length > 1000) {
            this.performanceMetrics[metricName].shift();
        }
    }

    // 样式优化系统
    setupStyleOptimization() {
        // CSS原子化工具
        this.setupAtomicCSS();
        
        // 样式污染检测
        this.setupStylePollutionDetection();
        
        // 关键CSS提取
        this.extractCriticalCSS();
    }

    // CSS原子化
    setupAtomicCSS() {
        const atomicClasses = {
            // 间距
            'm-0': 'margin: 0',
            'm-1': 'margin: 0.25rem',
            'm-2': 'margin: 0.5rem',
            'm-3': 'margin: 1rem',
            'p-0': 'padding: 0',
            'p-1': 'padding: 0.25rem',
            'p-2': 'padding: 0.5rem',
            'p-3': 'padding: 1rem',
            
            // 布局
            'd-flex': 'display: flex',
            'd-grid': 'display: grid',
            'd-none': 'display: none',
            'flex-column': 'flex-direction: column',
            'justify-center': 'justify-content: center',
            'align-center': 'align-items: center',
            
            // 颜色
            'text-primary': 'color: #007bff',
            'text-success': 'color: #28a745',
            'text-warning': 'color: #ffc107',
            'text-danger': 'color: #dc3545',
            'bg-primary': 'background-color: #007bff',
            'bg-light': 'background-color: #f8f9fa',
            
            // 文本
            'text-center': 'text-align: center',
            'text-left': 'text-align: left',
            'text-right': 'text-align: right',
            'font-bold': 'font-weight: bold',
            'font-normal': 'font-weight: normal'
        };

        // 动态生成原子CSS
        const style = document.createElement('style');
        style.textContent = Object.entries(atomicClasses)
            .map(([className, rules]) => `.${className} { ${rules} }`)
            .join('\n');
        
        document.head.appendChild(style);
        
        // 注册原子类
        this.styleRegistry.set('atomic', atomicClasses);
    }

    // 样式污染检测
    setupStylePollutionDetection() {
        // 检测全局样式污染
        const stylesheets = document.styleSheets;
        
        for (let i = 0; i < stylesheets.length; i++) {
            try {
                const rules = stylesheets[i].cssRules || [];
                
                for (let j = 0; j < rules.length; j++) {
                    const rule = rules[j];
                    
                    // 检测过于宽泛的选择器
                    if (rule.selectorText && this.isOverlyBroadSelector(rule.selectorText)) {
                        console.warn(`检测到可能造成样式污染的选择器: ${rule.selectorText}`);
                    }
                    
                    // 检测!important滥用
                    if (rule.style && rule.style.cssText.includes('!important')) {
                        console.warn(`检测到!important使用: ${rule.selectorText}`);
                    }
                }
            } catch (e) {
                // 跨域样式表无法访问
            }
        }
    }

    // 判断是否过于宽泛的选择器
    isOverlyBroadSelector(selector) {
        const broadSelectors = [
            /^\*$/,
            /^body$/,
            /^html$/,
            /^div$/,
            /^span$/,
            /^p$/,
            /^a$/,
            /^input$/,
            /^button$/
        ];
        
        return broadSelectors.some(regex => regex.test(selector));
    }

    // 关键CSS提取
    extractCriticalCSS() {
        // 这里可以实现关键CSS的提取和注入
        // 实际项目中可以使用工具如critical、penthouse等
        console.log('关键CSS提取功能已准备');
    }

    // 错误追踪
    setupErrorTracking() {
        window.addEventListener('error', (event) => {
            this.trackError({
                type: 'RUNTIME_ERROR',
                message: event.message,
                filename: event.filename,
                lineno: event.lineno,
                colno: event.colno,
                stack: event.error?.stack
            });
        });

        window.addEventListener('unhandledrejection', (event) => {
            this.trackError({
                type: 'PROMISE_REJECTION',
                reason: event.reason,
                stack: event.reason?.stack
            });
        });
    }

    // 错误追踪记录
    trackError(errorInfo) {
        const errorLog = {
            ...errorInfo,
            timestamp: Date.now(),
            userAgent: navigator.userAgent,
            url: window.location.href,
            viewport: `${window.innerWidth}x${window.innerHeight}`
        };

        console.error('前端错误:', errorLog);
        
        // 这里可以发送到错误监控服务
        this.sendToErrorService(errorLog);
    }

    // 发送错误到监控服务
    sendToErrorService(errorLog) {
        // 实际项目中可以集成Sentry、Bugsnag等
        fetch('/api/errors', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(errorLog)
        }).catch(() => {
            // 错误发送失败，静默处理
        });
    }

    // 懒加载优化
    setupLazyLoading() {
        // 图片懒加载
        this.lazyLoadImages();
        
        // 组件懒加载
        this.setupComponentLazyLoading();
        
        // 路由懒加载
        this.setupRouteLazyLoading();
    }

    // 图片懒加载
    lazyLoadImages() {
        const lazyImages = [].slice.call(document.querySelectorAll('img[data-src]'));
        
        if ('IntersectionObserver' in window) {
            const imageObserver = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const img = entry.target;
                        img.src = img.dataset.src;
                        img.removeAttribute('data-src');
                        imageObserver.unobserve(img);
                    }
                });
            });

            lazyImages.forEach(img => imageObserver.observe(img));
        } else {
            // 回退方案：直接加载所有图片
            lazyImages.forEach(img => {
                img.src = img.dataset.src;
            });
        }
    }

    // 组件懒加载
    setupComponentLazyLoading() {
        // 动态导入组件
        window.lazyLoadComponent = (componentName) => {
            return import(`./components/${componentName}.js`)
                .then(module => module.default)
                .catch(error => {
                    console.error(`组件加载失败: ${componentName}`, error);
                    return null;
                });
        };
    }

    // 路由懒加载
    setupRouteLazyLoading() {
        // 这里可以实现基于路由的代码分割
        console.log('路由懒加载功能已准备');
    }

    // 获取性能报告
    getPerformanceReport() {
        const calculateStats = (values) => {
            if (values.length === 0) return { average: 0, p95: 0, p99: 0, max: 0 };
            
            const sorted = values.map(v => v.value).sort((a, b) => a - b);
            const average = sorted.reduce((a, b) => a + b, 0) / sorted.length;
            const p95 = sorted[Math.floor(sorted.length * 0.95)];
            const p99 = sorted[Math.floor(sorted.length * 0.99)];
            const max = Math.max(...sorted);
            
            return { average, p95, p99, max };
        };

        return {
            pageLoad: calculateStats(this.performanceMetrics.pageLoadTimes),
            apiResponse: calculateStats(this.performanceMetrics.apiResponseTimes),
            memoryUsage: calculateStats(this.performanceMetrics.memoryUsage),
            interactionDelays: calculateStats(this.performanceMetrics.interactionDelays)
        };
    }

    // 清理无用资源
    cleanup() {
        // 清理事件监听器
        // 清理定时器
        // 释放内存
        console.log('前端优化器清理完成');
    }
}

// 状态管理优化
class StateManager {
    constructor() {
        this.state = {};
        this.listeners = new Map();
        this.history = [];
        this.maxHistorySize = 100;
    }

    // 设置状态
    setState(key, value) {
        const oldValue = this.state[key];
        this.state[key] = value;
        
        // 记录状态变更历史
        this.history.push({
            timestamp: Date.now(),
            key,
            oldValue,
            newValue: value
        });
        
        // 限制历史记录大小
        if (this.history.length > this.maxHistorySize) {
            this.history.shift();
        }
        
        // 通知监听器
        this.notifyListeners(key, value, oldValue);
    }

    // 获取状态
    getState(key) {
        return this.state[key];
    }

    // 订阅状态变化
    subscribe(key, listener) {
        if (!this.listeners.has(key)) {
            this.listeners.set(key, new Set());
        }
        
        this.listeners.get(key).add(listener);
        
        // 返回取消订阅函数
        return () => {
            this.unsubscribe(key, listener);
        };
    }

    // 取消订阅
    unsubscribe(key, listener) {
        const keyListeners = this.listeners.get(key);
        if (keyListeners) {
            keyListeners.delete(listener);
            if (keyListeners.size === 0) {
                this.listeners.delete(key);
            }
        }
    }

    // 通知监听器
    notifyListeners(key, newValue, oldValue) {
        const keyListeners = this.listeners.get(key);
        if (keyListeners) {
            keyListeners.forEach(listener => {
                try {
                    listener(newValue, oldValue);
                } catch (error) {
                    console.error('状态监听器执行错误:', error);
                }
            });
        }
    }

    // 状态回滚
    rollback(steps = 1) {
        if (this.history.length < steps) {
            console.warn('回滚步数超过历史记录');
            return false;
        }
        
        for (let i = 0; i < steps; i++) {
            const change = this.history.pop();
            if (change) {
                this.state[change.key] = change.oldValue;
                this.notifyListeners(change.key, change.oldValue, change.newValue);
            }
        }
        
        return true;
    }

    // 获取状态快照
    getSnapshot() {
        return JSON.parse(JSON.stringify(this.state));
    }

    // 从快照恢复
    restoreSnapshot(snapshot) {
        this.state = JSON.parse(JSON.stringify(snapshot));
        
        // 通知所有监听器
        Object.keys(this.state).forEach(key => {
            this.notifyListeners(key, this.state[key], undefined);
        });
    }
}

// 导出优化器
window.FrontendOptimizer = FrontendOptimizer;
window.StateManager = StateManager;

// 自动初始化
if (typeof window !== 'undefined') {
    window.frontendOptimizer = new FrontendOptimizer();
    window.stateManager = new StateManager();
}

export { FrontendOptimizer, StateManager };